//
//  UWHistoryManager.m
//  Urban Words
//
//  Created by sebastian on 2011-12-05.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "UWHistoryManager.h"
#import "UWHistoryCell.h"
#import "UWApi.h"
#import "UWFriendDetailHistory.h"
#import "UWHistoryController.h"

@implementation UWHistoryManager

- (id)initWithDelegate:(id<SectionHeaderViewDelegate>)delegate {
    self = [super init];
    allCells = [[NSMutableArray alloc] init];
    historyTable = delegate;
    /*
    for (int i=0; i<10; i=i+1) {
        UWHistoryCell *tmp2 = [[UWHistoryCell alloc] initWithLeftOrRight:(i%2?TRUE:FALSE) section:[NSNumber numberWithInt:i].integerValue delegate:delegate];
        [tmp2 setWords:[NSArray arrayWithObjects:@"hejsan", @"ass", @"karlsson",@"nej", @"boxy", @"solenoid", @"asscake", nil] score:@"0"];
        [allCells addObject:tmp2];
        [tmp2 release];
        i=i+1;
        tmp2 = [[UWHistoryCell alloc] initWithLeftOrRight:(i%2?TRUE:FALSE) section:[NSNumber numberWithInt:i].integerValue delegate:delegate];
        [tmp2 setWords:[NSArray arrayWithObjects:@"nej", @"boxy", @"solenoid", @"asscake", nil] score:@"0"];
        [allCells addObject:tmp2];
        [tmp2 release];
    }
    */
    return self;
}


- (id)initGameHistoryWithGameid:(NSString *)gameid delegate:(id<SectionHeaderViewDelegate>)delegate {
    self = [self initWithDelegate:delegate];
    /*
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.sypreme.se/uw/api/gamehistory/%@", gameid]];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (connection) {
        // NSLog(@"request sent");
    }
    else {
        NSLog(@"connection failed");
    }
    */
    
    //[UWApi call:[NSString stringWithFormat:@"gamehistory/%@", gameid] delegate:self];
    
    NSLog(@"send friend history req");
    [UWApi read:[NSString stringWithFormat:@"gamehistory/%@",gameid] listener:self action:@selector(gotGameHistory:)];
    
    return self;
}
- (id)initFriendHistoryWithFriend:(NSString *)fid delegate:(id<SectionHeaderViewDelegate>)delegate {
    self = [self initWithDelegate:delegate];
    
    /*
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.sypreme.se/uw/api/userhistory/%@", fid]];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    [UWApi call:[NSString stringWithFormat:@"userhistory/%@", fid] delegate:self];
    
    if (connection) {
        NSLog(@"request sent");
    }
    else {
        NSLog(@"connection failed");
    }
    */
    NSLog(@"send friend history req");
    [UWApi read:[NSString stringWithFormat:@"userhistory/%@",fid] listener:self action:@selector(gotFriendHistory:)];

    
    return self;
}

- (UWHistoryCell *)getHeaderAtSection:(NSInteger)section {
    return [allCells objectAtIndex:section];
}

- (UILabel *)getDefFromHeaderAtSection:(NSInteger)section {
    return [[allCells objectAtIndex:section] getExplanation];
}

- (NSUInteger)count {
    return [allCells count];
}

- (CGFloat)rowheightForHeaderAtSection:(NSInteger)section {
    return [[allCells objectAtIndex:section] getRowHeight];
}

- (NSString *)getDefinitionOfWord:(NSString *)word {
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.urbandictionary.com/iphone/search/define?term=%@", word]];
    
    //NSLog(@"URL: %@", url);
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (connection) {
        // NSLog(@"request sent");
    }
    else {
        NSLog(@"connection failed");
    }
    
    //[UWApi define:word delegate:self];
    
    return nil;
}

// Connection
/*
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
    //NSLog(@"Loading games");
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    //NSLog(@"Response games %d", [((NSHTTPURLResponse *)response) statusCode]);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Fail definition: %@", error);
    [connection release];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [connection release];
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    id tmp = [UWApi parseJson:data];
    NSLog(@"connection data: %@",tmp);
    if ([[tmp valueForKey:@"gamehistory"] isEqualToString:@"ok"]) {
        // It's a game.
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSArray *tmpDict = [tmp objectForKey:@"message"];
        NSInteger i = 0;
        for (NSDictionary *o in tmpDict) {
            BOOL right = [[defaults objectForKey:@"Fid"] isEqualToString:[o objectForKey:@"player"]];
            NSLog(@"%@", right?@"yes":@"no");
            UWHistoryCell *tmpCell = [[UWHistoryCell alloc] initWithLeftOrRight:right?NO:YES section:i delegate:historyTable];
            [tmpCell setWords:[o objectForKey:@"words"] score:[o objectForKey:@"score"]];
            [allCells addObject:tmpCell];
            [tmpCell release];
            i=i+1;
        }
        [tmpDict release];
    } else if ([[tmp valueForKey:@"userhistory"] isEqualToString:@"ok"]) {
        // It's a friend.
        NSArray *tmpDict = [tmp objectForKey:@"message"];
        NSInteger i = 0;
        for (NSDictionary *o in tmpDict) {
            UWHistoryCell *tmpCell = [[UWHistoryCell alloc] initWithLeftOrRight:YES section:i delegate:historyTable];
            [tmpCell setWords:[o objectForKey:@"words"] score:[o objectForKey:@"score"]];
            [allCells addObject:tmpCell];
            [tmpCell release];
            i=i+1;
        }
        [tmpDict release];
    }
}
*/

- (void)gotFriendHistory:(NSData *)data {
    allCells = [[NSMutableArray alloc] init];
    NSLog(@"got friend history");
    id tmp = [UWApi parseJson:data];
    if ([[tmp valueForKey:@"userhistory"] isEqualToString:@"ok"]) {
        // It's a friend.
        NSArray *tmpDict = [tmp objectForKey:@"message"];
        NSInteger i = 0;
        for (NSDictionary *o in tmpDict) {
            UWHistoryCell *tmpCell = [[UWHistoryCell alloc] initWithLeftOrRight:YES section:i delegate:historyTable];
            [tmpCell setWords:[o objectForKey:@"words"] score:[o objectForKey:@"score"]];
            [allCells addObject:tmpCell];
            [tmpCell release];
            i=i+1;
        }
        NSLog(@"number of cells: %i", [allCells count]);
        NSLog(@"end for loop: %i",i);
        //[tmpDict release];
    } else {
        NSLog(@"userhistory okay");
    }
    [(UWFriendDetailHistory *)historyTable updateTable];
}


- (void)gotGameHistory:(NSData *)data {
    id tmp = [UWApi parseJson:data];
    //NSLog(@"connection data: %@",tmp);
    if ([[tmp valueForKey:@"gamehistory"] isEqualToString:@"ok"]) {
        // It's a game.
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSArray *tmpDict = [tmp objectForKey:@"message"];
        NSInteger i = 0;
        for (NSDictionary *o in tmpDict) {
            BOOL right = [[defaults objectForKey:@"Fid"] isEqualToString:[o objectForKey:@"player"]];
            //NSLog(@"%@", right?@"yes":@"no");
            UWHistoryCell *tmpCell = [[UWHistoryCell alloc] initWithLeftOrRight:right?NO:YES section:i delegate:historyTable];
            [tmpCell setWords:[o objectForKey:@"words"] score:[o objectForKey:@"score"]];
            [allCells addObject:tmpCell];
            [tmpCell release];
            i=i+1;
        }
        //[tmpDict release];
    }
    //[tmp release];
    [(UWHistoryController *)historyTable updateTable];
}


@end
